<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5地理定位简单例子</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>

    <div id="geolocation">
        <h3>您的地理位置信息如下：</h3>
        <p>经度：{{info.longitude}}纬度：{{info.latitude}}</p>
        <p v-show="info.error != null">{{info.error}}</p>
        <p>
            <button type="button" @click.stop="getLocation">获取</button>
        </p>
    </div>

    <script>

        var geolocation = new Vue({
            el: '#geolocation',
            data: {
                info: {    //当前地理位置信息
                    latitude: null,  //纬度
                    longitude: null, //经度
                    error: null,   //错误信息
                },
                options: {  //地理位置配置选项
                    maximumAge: 60000, 
                    timeout: 5000, 
                    enableHighAccuracy: true 
                }
            },
            mounted() {

            },
            methods: {
                //获取当前地理定位信息
                getLocation() {
                    //判断浏览器是否支持navigator.geolocation地理定位功能
                    if (navigator.geolocation) {
                        //支持则执行showPosition方法，不支持则执行showError方法
                        navigator.geolocation.getCurrentPosition(this.showPosition, this.showError, this.options);
                    } else {    //不支持报错
                        this.info.error = "Geolocation is not supported by this browser.";
                    }
                },
                //经度回调函数
                showPosition(position) {             //显示地理定位的方法
                    console.log(position);
                    this.info.latitude = position.coords.latitude;
                    this.info.longitude = position.coords.longitude;
                },
                //错误处理回调函数
                showError(error) {               //报错信息方法
                    console.log(error);
                    switch (error.code) {
                        case error.PERMISSION_DENIED:
                            this.info.error = "无法定位用户位置."
                            break;
                        case error.POSITION_UNAVAILABLE:
                            this.info.error = "位置信息不可用."
                            break;
                        case error.TIMEOUT:
                            this.info.error = "用户定位请求超时."
                            break;
                        case error.UNKNOWN_ERROR:
                            this.info.error = "发生未知错误."
                            break;
                    }
                }
            }
        });
    </script>
</body>

</html>